﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using SnakeShop.Model.ViewModels.Basics;
using SnakeShop.Model.ViewModels.UI;

namespace SnakeShop.Admin.Infrastructure
{

    /// <summary>
    /// 请求验证错误处理
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]
    public class RequiredErrorForAdmin : ResultFilterAttribute
    {

        public override void OnResultExecuting(ResultExecutingContext context)
        {
            var modelState = context.ModelState;
            List<ErrorView> errors = new List<ErrorView>();
            if (!modelState.IsValid)
            {
                var baseResult = new AdminUiCallBack()
                {
                    code = 1,
                    msg = "请提交必要的参数"
                };
                foreach (var key in modelState.Keys)
                {
                    var state = modelState[key];
                    if (state.Errors.Any())
                    {
                        ErrorView errorView = new ErrorView();
                    }
                }

                baseResult.data = errors;
                context.Result = new ContentResult()
                {
                    Content = JsonConvert.SerializeObject(baseResult),
                    ContentType = "application/json"
                };
            }

        }
    }
}
